/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.monitor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.moon.admin.framework.MoonConstants;
import com.moon.admin.framework.cache.CacheService;
import com.moon.admin.framework.domain.MoonPage;
import com.moon.admin.framework.secure.AuthUtils;
import com.moon.admin.framework.springmvc.domain.R;
import com.moon.admin.sys.cache.UserCache;
import com.moon.admin.sys.domain.query.UserQuery;
import com.moon.admin.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 在线用户
 * @author moon
 */
@RestController
@RequestMapping("/monitor/online")
@Api(value="在线用户",tags="在线用户")
public class OnlineUserController {

    @Autowired
    private CacheService cacheService;

    @PostMapping(value = "list")
    @ApiOperation(value="在线用户列表")
    public R<MoonPage<SysUserEntity>> onlineUser(@RequestBody UserQuery query) {
        IPage<SysUserEntity> page = new Page<SysUserEntity>(query.getPage(),query.getLimit());
        List<String> totalKeys = cacheService.getKeyByPrefix(MoonConstants.CACHE_AUTH_INFO);
        page.setTotal(totalKeys.size());
        List<String> keys = totalKeys.stream().skip(query.getStart()* query.getLimit()).limit(query.getLimit()).collect(Collectors.toList());
        List<SysUserEntity> list = Lists.newArrayList();
        for(String key:keys){
            String userId = key.split(MoonConstants.CACHE_AUTH_INFO)[1];
            SysUserEntity user = UserCache.getUserById(Integer.valueOf(userId));
            user.setTokenId(key);
            list.add(user);
        }
        page.setRecords(list);
        return R.success(MoonPage.of(page));
    }
}
